package cn.tedu.ivos.base.file;

import cn.tedu.ivos.base.response.JsonResult;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("/v1/file/")
@Tag(name = "图片上传模块")
@Slf4j
public class UploadController {

    @Operation(summary = "图片上传功能")
    @ApiOperationSupport(order = 10)
    @PostMapping("upload")
    public JsonResult upload(@RequestBody MultipartFile  file) throws IOException {
        log.debug("图片上传业务");

        // 获取原始文件名
        String fileName = file.getOriginalFilename();
        log.debug("上传的文件名：{}", fileName);

        // 提取文件扩展名（包含点号）
        String suffix = fileName != null ? fileName.substring(fileName.lastIndexOf(".")) : null;

        // 使用 UUID 生成不重复的新文件名
        fileName = UUID.randomUUID() + suffix;

        // 设置基础存储路径
        String dirPath = "D:/files/";

        // 按照当前日期格式化子目录路径
        SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
        String datePath = sdf.format(new Date());

        // 构建完整目录对象并检查是否存在，不存在则创建
        File dir = new File(dirPath + datePath);
        if (!dir.exists()) {
            dir.mkdirs(); // 创建多级目录
        }

        // 构建最终文件路径
        String filePath = dirPath + datePath + fileName;

        // 将上传的文件写入目标路径
        file.transferTo(new File(filePath));

        // 返回成功响应，携带文件路径
        return JsonResult.ok(datePath+fileName);
    }

    @PostMapping("remove")
    @Operation(summary = "删除图片")
    @ApiOperationSupport(order = 20)
    public JsonResult removeFile(String imgUrl){
        log.debug("删除图片业务,imgUrl={}", imgUrl);
        new File("d:/files"+imgUrl).delete();
        return JsonResult.ok();
    }
}
